package org.vincent.ribbon;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractServerList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class CustomServerList extends AbstractServerList<CustomServer> {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private final String REGISTER_LIST_KEY = "register_list";

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }

    @Override
    public List<CustomServer> getInitialListOfServers() {
        return getServers();
    }

    @Override
    public List<CustomServer> getUpdatedListOfServers() {
        return getServers();
    }

    private List<CustomServer> getServers() {
        Set<String> members = redisTemplate.opsForSet().members(REGISTER_LIST_KEY);
        if (CollectionUtils.isEmpty(members)) {
            return Collections.emptyList();
        }

        return members.stream().map(i -> {
            try {
                return new CustomServer(new ObjectMapper().readValue(i, Instance.class));
            } catch (IOException e) {
                log.error("Error occur during get servers.", e);
                return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }

}
